package edu.neu.javaweb.utils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtil {
    private final static String URL = "jdbc:mysql://146.56.213.198:3306/hr?characterEncoding=utf-8&serverTimezone=GMT%2B8";
    private final static String USERNAME = "test";
    private final static String PASSWORD = "test";
    private Connection connection = null;
    private Statement statement = null;
    private static DBUtil dbUtil = null;

    private DBUtil() {
        try {
            // JDBC访问数据库取得用户名及密码
            // 1. 添加驱动到工程
            // 2. 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 3. 创建连接2
            connection = DriverManager.getConnection(
                    URL,
                    USERNAME,
                    PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static DBUtil getInstance() {
        if (dbUtil == null)
            dbUtil = new DBUtil();
        return dbUtil;
    }

    public static Connection getConnection() {
        return getInstance().connection;
    }

    public ResultSet query(String sql, Object... params) {
        ResultSet resultSet = null;

        try {
            // 4. 创建Statement
            PreparedStatement ps = dbUtil.getConnection().prepareStatement(sql);
            for (int i = 1; i <= params.length; i++) {
                ps.setObject(i, params[i - 1]);
            }
//            statement = connection.createStatement();
            // 5. 执行查询
//            resultSet = statement.executeQuery(sql);
            resultSet = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    public boolean modify(String sql, Object... params) {
        boolean result = false;
        try {
            // 4. 创建Statement
            PreparedStatement ps = dbUtil.getConnection().prepareStatement(sql);
            for (int i = 1; i <= params.length; i++) {
                ps.setObject(1, params[i]);
            }
//            statement = connection.createStatement();
            // 5. 执行查询
//            result = statement.execute(sql);
            result = ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        // 7. 关闭资源
        try {
            if (connection != null) connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
